package com.github.tvbox.osc.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.tvbox.osc.ui.activity.RecWordHelper
import com.github.tvbox.osc.viewmodel.SourceViewModel.MediaCategoryTask
import com.github.tvbox.osc.viewmodel.SourceViewModel.MediaSearchTask
import io.github.source.config.VodConfig
import io.github.source.media.bean.MediaBean
import io.github.source.media.bean.MediaCategory
import io.github.source.media.bean.MediaResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @ClassName: SourceViewModelKt
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: huangrongcai
 * @date: 2025/7/11
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class SourceViewModelKt : ViewModel() {

    private val _categoryResult = MutableLiveData<MediaResult<List<MediaCategory?>?>?>()
    val categoryResult: LiveData<MediaResult<List<MediaCategory?>?>?> get() = _categoryResult

    private val _searchResult = MutableLiveData<MediaResult<List<MediaBean>>>()
    val searchResult: LiveData<MediaResult<List<MediaBean>>> get() = _searchResult

    private val _queryWord = MutableLiveData<List<String>>()
    val queryWord: MutableLiveData<List<String>> get() = _queryWord

    fun fetchCategory() {
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO) {
                VodConfig.get().initConfigSync()
                MediaCategoryTask().call()
            }
            _categoryResult.postValue(result)
        }
    }

    fun fetchSearch(siteKey: String, keyword: String) {
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO) {
                VodConfig.get().initConfigSync()
                MediaSearchTask(siteKey, keyword).call()
            }
            _searchResult.postValue(result)
        }
    }

    fun fetchRecWords(keyword: String) {
        viewModelScope.launch {
            VodConfig.get().initConfigSync()
            RecWordHelper.loadRecWord(keyword, _queryWord)
        }
    }
}